package com.template.config.webmvc.interceptor;

import com.template.common.exception.CommonException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * 文件大小限制拦截器
 */
@Component
public class FileUploadInterceptor implements HandlerInterceptor {

    @Value("${spring.servlet.file.max-single-size}")
    private Integer maxSingleSize;

    @Value("${spring.servlet.file.max-total-size}")
    private Integer maxTotalSize;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (request instanceof MultipartHttpServletRequest multipartRequest) {
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

            double totalSize = 0;
            for (MultipartFile file : fileMap.values()) {
                // 获取文件大小并将单位转为MB，保留两位小数
                double fileSize = Math.round((double) file.getSize() / 10485.76) / 100.0;
                if (fileSize > maxSingleSize) {
                    String msg = String.format("上传文件过大 [单文件大小不得超过 %sMB，当前文件大小为 %sMB]", maxSingleSize, fileSize);
                    throw new CommonException(msg);
                }
                totalSize += fileSize;
            }
            if (totalSize > maxTotalSize) {
                String msg = String.format("上传文件过大 [上传总文件大小不得超过 %sMB，当前文件大小为 %sMB]", maxSingleSize, totalSize);
                throw new CommonException(msg);
            }
        }

        return true;
    }
}
